package com.rdc.example.service.impl;

import com.rdc.example.bean.PageBean;
import com.rdc.example.bean.Result;
import com.rdc.example.bean.dto.PlayListDTO;
import com.rdc.example.dao.PlayListSongDao;
import com.rdc.example.dao.impl.PlayListDaoImpl;
import com.rdc.example.dao.impl.PlayListSongDaoImpl;
import com.rdc.example.dao.impl.UserDaoImpl;
import com.rdc.example.entity.PlayList;
import com.rdc.example.entity.User;
import com.rdc.example.util.FileUtil;
import org.apache.commons.fileupload.FileItem;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.rdc.example.util.FileUtil.uploadFile;

public class PlayListServiceImpl implements com.rdc.example.service.PlayListService {

    PlayListDaoImpl playListDao = new PlayListDaoImpl();
    PlayListSongDaoImpl playListSongDao = new PlayListSongDaoImpl();
    UserDaoImpl userDao = new UserDaoImpl();

    @Override
    public Result insertPlayList(PlayListDTO playListDTO, List<FileItem> fileItems) throws Exception {
        PlayList playListEntity = convertToEntity(playListDTO);
        Result fileResult=uploadFile(fileItems,0);
        if (fileResult.getCode()==200){
            //如果上传成功，就存入playList
            playListEntity.setCoverPath((String) fileResult.getData());
        }
        boolean register = playListDao.insert(playListEntity);
        return register ? Result.success("创建成功", null)
                : Result.fail("创建失败", null);
    }

    @Override
    public Result deletePlayList(Integer userId, Integer playListId) throws Exception {
        if (userId == null || playListId == null) {
            return Result.fail("userId或playListId不为空", null);
        }
        //获取用户
        User user = userDao.getUserById(userId);
        //获取歌单
        PlayList playList = playListDao.getPlayListById(playListId);
        //权限检测 是不是自己的，是不是管理员
        if (user.getId().equals(playList.getUserId()) || user.getUserType() == 3) {

             return Result.fail("权限不足", null);

        }  //歌单对应的记录清空
        //playListSong.deleteAll(playlistId);
        //删除歌单
        boolean deletePlayList = playListDao.deleteById(playListId);
        if (!deletePlayList) {
            Result.fail("删除失败", null);
        }
        boolean deleteFile = FileUtil.deleteFile(playList.getCoverPath());
        return deleteFile ? Result.success("删除成功", null)
                : Result.fail("歌曲信息删除成功，文件删除失败", null);
    }

    @Override
    public Result updatePlayList(PlayListDTO playListDTO) throws Exception {
        PlayList playListEntity = convertToEntity(playListDTO);
        boolean register = playListDao.update(playListEntity);
        return register ? Result.success("修改成功", null)
                : Result.fail("修改失败", null);
    }

    public Result getRandomPlayList() throws Exception {
        PlayList playList = playListDao.getRandomPlayList();
        //单独补充用户名称
        User user=userDao.getUserById(playList.getUserId());
        PlayListDTO playListDTO=convertToDto(playList);
        playListDTO.setUserName(user.getUserName());
        return  Result.success("获取成功",playListDTO);
    }

    @Override
    public Result turnInOrOutPlaylist(Integer playListId, Integer songId) throws Exception {
         if (playListId == null || songId == null) {
             return Result.fail("songId或userId为空", null);
         }
         if (playListSongDao.check(playListId, songId)) {
             // 在playList里面,移除
             boolean register=playListSongDao.delete(playListId, songId);
             //返回结果
             return register ? Result.success("移除成功", null)
                     : Result.fail("移除失败", null);
         } else {
             // 不在playList里面,移入
             boolean register= playListSongDao.insert(playListId, songId);
             //返回结果
             return register ? Result.success("移入成功", null)
                     : Result.fail("移入失败", null);
         }
    }


    @Override
    public PageBean<PlayListDTO> getPlayListListByUserId(Integer userId, Integer currentPage, Integer pageSize) throws Exception {
        if (userId == null || currentPage == null || pageSize == null) {
            return null;
        }
        Integer pageBegin = (currentPage - 1) * pageSize;
        // 调用 dao 获取数据
        List<PlayList> playListList = playListDao.getPlayListsByPageAndUserId(userId, pageBegin, pageSize);
        Integer totalCount = playListDao.countPlayListByUserId(userId);
        // 封装 PageBean
        PageBean<PlayListDTO> pageBean = new PageBean<>();
        pageBean.setTotalCount(totalCount);
        pageBean.setRows(convertAndEnrichPlayLists(playListList));
        return pageBean;
    }

    @Override
    public PageBean<PlayListDTO> searchPlaylistsByTitle(String keyword, Integer currentPage, Integer pageSize) throws Exception {
        Integer pageBegin = (currentPage - 1) * pageSize;
        // 调用 dao
        List<PlayList> playlistList = playListDao.searchPlaylistsByTitle(keyword, pageBegin, pageSize);
        Integer totalCount = playListDao.countSearchPlaylistsByTitle(keyword);
        // 封装 PageBean
        PageBean<PlayListDTO> pageBean = new PageBean<>();
        pageBean.setTotalCount(totalCount);
        pageBean.setRows(convertAndEnrichPlayLists(playlistList));
        return pageBean;
    }





    private List<PlayListDTO> convertAndEnrichPlayLists(List<PlayList> playListEntityList) throws SQLException {
        List<PlayListDTO> dtos = new ArrayList<>();
        Set<Integer> userIds = playListEntityList.stream()
                .map(PlayList::getUserId)
                .collect(Collectors.toSet());
        UserDaoImpl userDao = new UserDaoImpl();
        Map<Integer, User> userMap = userDao.getUsersByIds(userIds);
        // 转换并填充作者信息
        for (PlayList entity : playListEntityList) {
            PlayListDTO dto = convertToDto(entity);
            User user = userMap.get(entity.getUserId());
            if (user != null) {
                dto.setUserName(user.getUserName());
            } else {
                dto.setUserName("未知");
                System.err.println("用户不存在: userId=" + entity.getUserId());
            }
            dtos.add(dto);
        }
        return dtos;
    }

    private PlayListDTO convertToDto(PlayList entity) {
        PlayListDTO dto = new PlayListDTO();
        dto.setId(entity.getId());
        dto.setUserId(entity.getUserId());
        dto.setName(entity.getName());
        dto.setCoverPath(entity.getCoverPath());
        dto.setIsLike(entity.getIsLike());
        dto.setIsPublic(entity.getIsPublic());
        dto.setCreatedAt(entity.getCreatedAt());
        return dto;
    }

    private PlayList convertToEntity(PlayListDTO dto) {
        PlayList entity = new PlayList();
        entity.setId(dto.getId());
        entity.setUserId(dto.getUserId());
        entity.setName(dto.getName());
        entity.setCoverPath(dto.getCoverPath());
        entity.setIsLike(dto.getIsLike());
        entity.setIsPublic(dto.getIsPublic());
        entity.setCreatedAt(dto.getCreatedAt());
        return entity;
    }


}
